import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created by codeczx on 2018/3/21.
 */
public class LogService {

    private final BlockingQueue<String> msgQueue;
    private final LoggerThread loggerThread;
    private PrintWriter printWriter;
    private boolean isShutdown;
    private int reservations;

    LogService() {
        msgQueue = new LinkedBlockingDeque<>(5);
        loggerThread = new LoggerThread();
        try {
            printWriter = new PrintWriter(new File("log.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        loggerThread.start();
    }

    public void log(String msg) throws InterruptedException {
        synchronized (this) {
            if (!isShutdown) {
                reservations++;
            } else {
                throw new IllegalStateException("logService is shutdown");
            }
        }
        msgQueue.put(msg);
    }

    public void stop() {
        synchronized (this) {
            isShutdown = true;
        }
        loggerThread.interrupt();
    }

    class LoggerThread extends Thread {
        @Override
        public void run() {
            try {
                while (true) {
                    if (isShutdown && reservations == 0) {
                        break;
                    }
                    try {
                        String takeStr = LogService.this.msgQueue.take();
                        System.out.println("take " + takeStr);
                        printWriter.write(takeStr);
                    } catch (InterruptedException e) {
                        System.out.println("logger thread interrupt");
                        e.printStackTrace();
                    }
                }
            } finally {
                printWriter.close();
            }
        }
    }
}
